package com.stox.ui.swing.widget;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

public class TableModel extends AbstractTableModel {
	private static final long serialVersionUID = -4328933822275099320L;

	private List<?> list;
	private Class<?> clazz;
	private Method[] getters = new Method[0];
	
	public TableModel(List<?> list) {
		this.list = list;
		if(list != null && !list.isEmpty()){
			clazz = list.get(0).getClass();
			Method[] methods = clazz.getMethods();
			List<Method> mList = new ArrayList<Method>();
			for(Method method : methods){
				if(method.getName().startsWith("get") 
						&& method.getParameterTypes().length == 0
						&& method.isAccessible()){
					mList.add(method);
				}
			}
			getters = mList.toArray(getters);
		}
	}
	
	@Override
	public int getRowCount() {
		if(list == null){
			return 0;
		}
		return list.size();
	}

	@Override
	public int getColumnCount() {
		if(clazz == null){
			return 0;
		}
		return getters.length;
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		if(list == null || clazz == null){
			return null;
		}
		try {
			return getters[columnIndex].invoke(list.get(rowIndex), new Object[0]);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public Class<?> getColumnClass(int columnIndex) {
		if(clazz == null){
			return null;
		}
		return getters[columnIndex].getReturnType();
	}

}
